<?php

namespace App\Console\Commands;

use App\Article;
use App\Permission;
use App\Studyfav;
use App\Utils;
use Illuminate\Console\Command;
use DB;
use App\User;
use App\Comment;
use Auth;

//use Illuminate\Foundation\Inspiring;

class Calc extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'calc';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'calculate comment';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //if (!Auth::check()) return;
        //if (Permission::userid_is_norank(Auth::user()->id)) return;
        
		var_dump("articles begin:");
        $comments = Comment::all();
        foreach ($comments as $c) {
            $c->score = 0;
            $voted_users = Studyfav::where('studyid', $c->id)->where('type', 1)->groupBy('userid')->get();
            foreach ($voted_users as $user) {
                if ($c->userid === $user->userid)
                    continue;
                $factor = 1;
                if ($user->vote_type == 1) {
                    $factor = -1;
                }
                $user = User::find($user->userid);
                if ($user != null) {
                    $c->score += intval($factor * $user->score / 100);
                }
            }
            $c->save();
		}
		var_dump("comments cnt:".count($comments));
        $articles = Article::all();
        foreach ($articles as $article) {
            $article->score = 0;
            $voted_users = Studyfav::where('studyid', $article->id)->where('type', 2)->groupBy('userid')->get();
            foreach ($voted_users as $user) {
                if ($article->userid === $user->userid)
                    continue;
                $user = User::find($user->userid);
                if ($user != null) {
                    $article->score += intval($user->score / 100);
                }
            }
            $article->save();
        }
		var_dump("articles cnt:".count($articles));

    }
}
